<?php

declare(strict_types=1);

namespace App\Model;

use App\Helpers\ConfigUtil;
use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;

/**
 * 用户推荐
 */
class UserRecOnline extends Model
{
    protected $table = 'user_recommand_online';

    protected $fillable = [
        'user_id', 'rec_user_ids', 'flag'
    ];

    //未读
    const STATUS_UNREAD = 0;
    //已读
    const STATUS_READ = 1;

    /**
     * 单批次添加用户
     */
    static function addRecord($userId = 0, $recUserIds = [])
    {
        if (!$recUserIds) return false;
        if (!is_array($recUserIds)) $recUserIds = [$recUserIds];
        $ret = self::create([
            'user_id' => $userId,
            'rec_user_ids' => json_encode($recUserIds),
            'flag' => self::STATUS_UNREAD,
        ]);
        return $ret;
    }

    /**
     * 单个添加用户
     */
    static function addRecUser($userId = 0, $recUserId = 0)
    {
        $record = self::getRecord($userId);
        //无记录,新添加
        if (!$record) return self::addRecord($userId, $recUserId);
        $addTime = strtotime((string)$record->created_at);
        //超过统计周期,新添加
        if (time() >= ($addTime + ConfigUtil::getOnlineRecInterval())) {
            return self::addRecord($userId, $recUserId);
        }
        //统计周期内,更新记录
        $uids = json_decode($record->rec_user_ids, true);
        array_push($uids, $recUserId);
        $record->rec_user_ids = json_encode(array_values(array_unique($uids)));
        return $record->saveOrFail();
    }

    /**
     * 获取已经推荐过该用户的主播ID（当天）
     * @param $userId 被推荐的男用户
     * @param $recTimes 筛选推荐次数
     * 
     */
    static function getPushedHostIds($userId = 0, $recTimes = 1)
    {
        $where = [
            ['created_at', '>', date('Y-m-d')]
        ];
        $records = self::where($where)->select(['user_id', 'rec_user_ids'])->get()->toArray();
        $hostIds = [];
        array_walk($records, function ($record) use (&$hostIds, $userId) {
            $recUserIds = json_decode($record['rec_user_ids'], true);
            if (in_array($userId, $recUserIds)) {
                if (!isset($hostIds[$record['user_id']])) $hostIds[$record['user_id']] = 1;
                else $hostIds[$record['user_id']]++;
            }
        });
        if (!$hostIds) return [];
        $hostIds = array_filter($hostIds, function ($val) use ($recTimes) {
            return $val >= $recTimes;
        });
        return !$hostIds ? [] : array_keys($hostIds);
        // return !$hostIds ? [] : array_unique($hostIds);
    }

    /**
     * 获取记录
     */
    static function getList($userId = 0)
    {
        $items = self::where('user_id', $userId)->select(['rec_user_ids', 'created_at'])->orderBy('id', 'desc')->get()->toArray();
        $data = [];
        foreach ($items as $item) {
            $data[] = [
                'user_ids' => json_decode($item['rec_user_ids'], true),
                'rec_time' => (string)$item['created_at']
            ];
        }
        return $data;
    }

    /**
     * 获取新的个数
     */
    static function getNew($userId = 0)
    {
        return self::where(['user_id' => $userId, 'flag' => self::STATUS_UNREAD])->count();
    }

    /**
     * 获取最近的记录
     */
    static function getRecord($userId = 0)
    {
        return self::where(['user_id' => $userId])->orderBy('id', 'desc')->first();
    }
}
